package mo.tags.stack;

import java.util.Arrays;
import java.util.Stack;

public class L735 {

    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();
        for (int a : asteroids) {
            if (a > 0) {
                stack.push(a);
            } else {
                while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < -a) {
                    stack.pop();
                }
                if (stack.isEmpty() || stack.peek() < 0) {
                    stack.push(a);
                } else {
                    if (stack.peek() == -a) {
                        stack.pop();
                    }
                }
            }
        }
        int n = stack.size();
        int[] ret = new int[n];
        while (!stack.isEmpty()) {
            ret[n-1] = stack.pop();
            n--;
        }
        return ret;
    }

    public static void main(String[] args) {
        L735 test = new L735();
        System.out.println(Arrays.toString(test.asteroidCollision(new int[]{10,2,-5})));
    }

}
